import threading
import uuid
from flask import has_app_context, current_app, g
import logging


class LogUtils:
    local_data = threading.local()

    @staticmethod
    def add_trace_id():
        LogUtils.local_data.trace_id = str(uuid.uuid4())

    @staticmethod
    def info(msg: str):
        if has_app_context():
            current_app.logger.info(msg)
        else:
            gunicorn_logger = logging.getLogger('gunicorn.error')
            if hasattr(LogUtils.local_data, 'trace_id'):
                msg = f'[{LogUtils.local_data.trace_id}]-' + msg
            gunicorn_logger.info(msg)

    @staticmethod
    def error(msg: str):
        if has_app_context():
            current_app.logger.error(msg)
        else:
            gunicorn_logger = logging.getLogger('gunicorn.error')
            if hasattr(LogUtils.local_data, 'trace_id'):
                msg = f'[{LogUtils.local_data.trace_id}]-' + msg
            gunicorn_logger.error(msg)

    @staticmethod
    def exception(e: Exception, msg: str = ''):
        if has_app_context():
            current_app.logger.exception(e)
        else:
            gunicorn_logger = logging.getLogger('gunicorn.error')
            if hasattr(LogUtils.local_data, 'trace_id'):
                msg = f'[{LogUtils.local_data.trace_id}]-' + msg
            gunicorn_logger.exception(e)

    @staticmethod
    def warning(msg: str):
        if has_app_context():
            current_app.logger.warning(msg)
        else:
            gunicorn_logger = logging.getLogger('gunicorn.error')
            if hasattr(LogUtils.local_data, 'trace_id'):
                msg = f'[{LogUtils.local_data.trace_id}]-' + msg
            gunicorn_logger.warning(msg)

    @staticmethod
    def debug(msg: str):
        if has_app_context():
            current_app.logger.debug(msg)
        else:
            gunicorn_logger = logging.getLogger('gunicorn.error')
            if hasattr(LogUtils.local_data, 'trace_id'):
                msg = f'[{LogUtils.local_data.trace_id}]-' + msg
            gunicorn_logger.debug(msg)
